package com.example.environment.base.Transaction;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *  @author: wangbo(1141294273@qq.com)
 *  @Date: 2021/1/27 16:48
 *  @Description: 事务同步回滚
 */ 
public class TransactionUtil {
   private static Logger log = LoggerFactory.getLogger(TransactionUtil.class);
    //创建一个私有静态的并且是与事务相关联的局部线程变量
    private static ThreadLocal<Connection> connectionHolder = new ThreadLocal<>();

    @Value("${spring.datasource.url}")
    private static String url;

    @Value("${spring.datasource.user}")
    private static String user;

    @Value("${spring.datasource.password}")
    private static String password;

    @Value("${jwt.driver-class-name}")
    private static String driverClassName;

    /**
    * @Description 采用ThreadLocal封装Connection
    * @Author  wangbo
    * @Date   2021/1/27 16:51
    * @Param
    * @Return
    * @Exception
    *
    */
    public static Connection getConnection() {
        //获得线程变量connectionHolder的值conn
        Connection conn = connectionHolder.get();
        if (conn == null) {
            try {
                //创建jdbc连接
                 Class cla = Class.forName(driverClassName);
                 Driver driver = (Driver) cla.newInstance();
                 DriverManager.registerDriver(driver);
                  conn = DriverManager.getConnection(url, user, password);
                  connectionHolder.set(conn);
             } catch (Exception e) {
                log.error("创建db connection异常",e);
             }
        }
        return conn;

    }

    /**
    * @Description 关闭连接和从线程变量中删除conn
    * @Author  wangbo
    * @Date   2021/1/27 16:51
    * @Param  
    * @Return      
    * @Exception   
    * 
    */ 
    public static void closeConnection() {
        //获得线程变量connectionHolder的值conn
        Connection conn = connectionHolder.get();
        if (conn != null) {
            try {
                //关闭连接
                conn.close();
                //从线程局部变量中移除conn，如果没有移除掉，下次还会用这个已经关闭的连接，就会出错
                connectionHolder.remove();
            } catch (SQLException e) {
                log.error("关闭db connection异常",e);
            }
        }

    }



    /**
    * @Description 手动开始事务
    * @Author  wangbo
    * @Date   2021/1/27 16:53
    * @Param  conn
    * @Return
    * @Exception
    *
    */
    public static void beginTransaction(Connection conn){
        try {
            //如果连接存在，再设置连接，否则会出错
            if (conn != null){
                //默认conn是自动提交，
                if (conn.getAutoCommit()){
                    //关闭自动提交，即是手动开启事务
                    conn.setAutoCommit(false);
                }
            }
        }catch(SQLException e){
            log.error("开启事务异常",e);
        }
    }
    /**
    * @Description 提交事务
    * @Author  wangbo
    * @Date   2021/1/27 16:54
    * @Param  conn
    * @Return
    * @Exception
    *
    */
    public static void commitTransaction(Connection conn){
        try{
            if (conn != null){
                if (!conn.getAutoCommit()){
                    conn.commit();
                }
            }
        }catch(SQLException e){
            log.error("提交事务异常",e);
        }
    }



    /**
    * @Description 回滚事务
    * @Author  wangbo
    * @Date   2021/1/27 16:55
    * @Param
    * @Return
    * @Exception
    *
    */
    public static void rollbackTransaction(Connection conn){
        try {
            if (conn != null){
                if(!conn.getAutoCommit()){
                    conn.rollback();
                }
            }
        }catch(SQLException e){
            log.error("回滚事务异常",e);
        }
    }

}

